﻿using Microsoft.AspNetCore.SignalR.Client;
using NLog;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace shop.singlr
{
    /// <summary> 简单的 SignalR 客户端 </summary>
    public class BaseSignalRClient
    {
        /// <summary> 连接 </summary>
        public virtual HubConnection Connection { set; get; }


        protected ILogger _log = LogManager.GetCurrentClassLogger();


        protected Action<string> _displayStatus;

        /// <summary>  </summary>
        public virtual string HubUrl { get; set; }



        public BaseSignalRClient UseDisplayStatus(Action<string> displayStatus)
        {
            _displayStatus = displayStatus;
            return this;
        }


        public BaseSignalRClient UseUrl(string hubUrl)
        {
            HubUrl = hubUrl;
            return this;
        }




        /// <summary> 启动, 返回本身 </summary>
        public async Task<BaseSignalRClient> Start()
        {
            if (string.IsNullOrEmpty(HubUrl))
            {
                throw new Exception("没有 HubUrl 地址");
            }


            var baseUrl = myApp.GetClient().BaseUrl.Replace("api/", string.Empty)+"hubs/";



            // 创建连接
            Connection = new HubConnectionBuilder()
                .WithUrl(baseUrl+ HubUrl)
                .WithAutomaticReconnect()   //自动重连
                .WithKeepAliveInterval(new TimeSpan(0, 0, 30))
                .Build();


            //处理连接状态变化
            Connection.Reconnecting += async e =>
            {
                _displayStatus?.Invoke( "正在连接...");
                await Task.CompletedTask;
            };

            // 重连成功
            Connection.Reconnected += async e =>
            {
                _displayStatus?.Invoke(string.Empty);
                await Task.CompletedTask;
            };


            try
            {
                // 启动连接
                await Connection.StartAsync();

                _displayStatus?.Invoke(string.Empty);

            }
            catch (Exception ex)
            {
                _log.Error(ex);
                _displayStatus?.Invoke("连接已断开");
            }


            return this;
        }






        /// <summary>  </summary>
        public async Task Stop()
        {
            if (Connection != null)
                await Connection?.StopAsync();
        }



    }
}
